package cn.com.bluemoon.daps.common.validation.sql;

/**
 * @author Jarod.Kong
 * @date 2021/1/22 14:43
 */

import cn.com.bluemoon.daps.common.toolkit.HiveUtil;
import cn.com.bluemoon.daps.common.validation.JValidUtils;
import com.alibaba.druid.DbType;
import com.alibaba.druid.util.MySqlUtils;
import com.alibaba.druid.util.OracleUtils;
import com.alibaba.druid.util.PGUtils;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 检查字段中是否为数据库sql关键字
 * 1.初始化字典数据
 * 2.命中则判定为关键字
 * <pre>
 *      TestVo testVo = new TestVo();
 *      testVo.setId(null);
 *      testVo.setFieldName("case");
 *      List<String> validate = JValidUtils.INSTANCE.validate(testVo);
 *      System.out.println(validate);
 *      Assert.assertTrue(validate.size() > 0);
 *      save(testVo);
 * </pre>
 *
 * @author Jarod.Kong
 * @see JValidUtils#validate(Object)
 */
@Component
public class NoSqlKeywordValidator implements ConstraintValidator<NoSqlKeyword, CharSequence> {

    private DbType dbType;

    @Override
    public void initialize(NoSqlKeyword constraintAnnotation) {
        this.dbType = constraintAnnotation.dbtype();
    }

    /**
     * 有效性校验
     *
     * @param value   str
     * @param context 上下文
     * @return true 没有keyword， false 为数据库Sql keyword
     */
    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (DbType.mysql.equals(dbType)) {
            return !MySqlUtils.isKeyword(value.toString());
        }
        if (DbType.postgresql.equals(dbType)) {
            return !PGUtils.isKeyword(value.toString());
        }
        if (DbType.oracle.equals(dbType)) {
            return !OracleUtils.isKeyword(value.toString());
        }
        if (DbType.hive.equals(dbType)) {
            return !HiveUtil.isKeyword(value.toString());
        }
        return true;
    }

}